package cc.rengu.redp.bizimpl.upmp.controller;


import cc.rengu.redp.bizimpl.enums.PageOptFlagEnum;
import cc.rengu.redp.bizimpl.upmp.common.BusinessContainer;
import cc.rengu.redp.bizimpl.upmp.domain.AgentInfo;
import cc.rengu.redp.bizimpl.upmp.domain.AlipayInfo;
import cc.rengu.redp.bizimpl.upmp.domain.AreaInfo;
import cc.rengu.redp.bizimpl.upmp.domain.UpmpBMchntBaseInfo;
import cc.rengu.redp.bizimpl.upmp.service.IAgentInfoService;
import cc.rengu.redp.bizimpl.upmp.service.IFeeInfoService;
import cc.rengu.redp.bizimpl.upmp.service.IUpmpSysParamService;
import cc.rengu.redp.bizimpl.upmp.vo.OperationResult;
import cc.rengu.redp.bizimpl.upmp.vo.UpmpUserInfoVO;
import cc.rengu.redp.bizimpl.utils.Common;
import cc.rengu.redp.bizimpl.utils.CommonUtils;
import cc.rengu.redp.bizimpl.utils.GZIPUtils;
import cc.rengu.redp.common.annotation.Log;
import cc.rengu.redp.common.controller.BaseController;
import cc.rengu.redp.common.domain.QueryRequest;
import cc.rengu.redp.common.exception.RedpException;
import cc.rengu.redp.common.utils.SortUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotBlank;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 刘玉亮.LL
 */
@Slf4j
@Api(tags = "商户管理:代理机构信息")
@RestController
@RequestMapping(value = "/admin/merParam/agentInfo")
public class AgentInfoController extends BaseController {

    @Autowired
    private IAgentInfoService agentInfoService;
    @Autowired
    private IUpmpSysParamService upmpSysParamService;
    @Autowired
    private IFeeInfoService feeInfoService;

    private long oprMenuId = 20000019;
    private String oprMenuName = "商户管理:代理机构管理";
    private long chkMenuId = 20000019;
    private String chkMenuName = "商户管理:代理机构管理";
    private String webNextUrl = "/admin/merParam/agentInfo/edit";

    @GetMapping("/list")
    @RequiresPermissions("agentInfo:list")
    public Map<String, Object> list(QueryRequest request, AgentInfo entity) throws RedpException {
        return getDataTable(this.agentInfoService.findByPage(request, entity));
    }

    @Log("编辑查询")
    @GetMapping(value = "/edit")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "optFlag", value = "操作类型：新增、修改、删除、审核等", required = true, dataType = "String")
    })
    @RequiresPermissions(value = {"agentInfo:add","agentInfo:update","agentInfo:stop","agentInfo:use","agentInfo:delete","agentInfo:view"},logical = Logical.OR)
    public Map<String, Object> editShow(AgentInfo entity, String optFlag) throws RedpException {
        return agentInfoService.editShow(entity, optFlag);
    }


    //@RequiresPermissions("商户管理:代理机构管理")
    @PostMapping(value = "/edit")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "optFlag", value = "操作类型：新增、修改、删除、审核等", required = true, dataType = "String")
    })
    public OperationResult editSave(@ModelAttribute("agentInfo") AgentInfo entity, HttpServletRequest request) throws RedpException {
        String optFlag = request.getParameter("optFlag") == null ? "" : request.getParameter("optFlag");
        if (entity.getProfitConfInfoList() != null && !entity.getProfitConfInfoList().equals("")) {
            entity.setProfitConfInfoList(entity.getProfitConfInfoList().replaceAll("&quot;", "\""));
        }
        String menuId;
        if (PageOptFlagEnum.OPT_FLAG_CHECK.getType().equals(optFlag)) {
            menuId = String.valueOf(chkMenuId);
        } else {
            menuId = String.valueOf(oprMenuId);
        }
        return agentInfoService.saveData(menuId, oprMenuName, entity, request, webNextUrl);
    }


    /**
     * 审批
     *
     * @param entity
     * @param request
     * @return
     */


    //@RequiresPermissions("商户管理:代理机构管理")
    @PostMapping(value = "/editPass")

    public OperationResult editpass(@ModelAttribute("agentInfo") AgentInfo entity, HttpServletRequest request) throws RedpException {
        if (entity.getProfitConfInfoList() != null && !entity.getProfitConfInfoList().equals("")) {
            entity.setProfitConfInfoList(entity.getProfitConfInfoList().replaceAll("&quot;", "\""));
        }
        String id = request.getParameter("id");
        String optFlag = request.getParameter("optFlag");
        String auditRefuseReason = entity.getAuditRefuseReason();
        String cancelReason = entity.getCancelReason();
        String stopReason = entity.getStopReason();
        entity = agentInfoService.getById(id);
        entity.setAuditRefuseReason(auditRefuseReason);
        entity.setCancelReason(cancelReason);
        entity.setStopReason(stopReason);

        String menuId;
        if (PageOptFlagEnum.OPT_FLAG_CHECK.getType().equals(optFlag)) {
            menuId = String.valueOf(chkMenuId);
        } else {
            menuId = String.valueOf(oprMenuId);
        }

        return agentInfoService.chkData(menuId, oprMenuName, entity, request, webNextUrl);
    }


    @Log("删除")
    @DeleteMapping("/{ids}")
//    @RequiresPermissions("agentInfo:delete")
    @ApiImplicitParam(paramType = "path", name = "ids", value = "id主键，逗号隔开", required = true, dataType = "String")
    public void delete(@NotBlank(message = "{required}") @PathVariable String ids) throws RedpException {
        try {
            String[] idGroup = ids.split(StringPool.COMMA);
            for (String s : idGroup) {
                AgentInfo entity = agentInfoService.getById(s);
                String status = entity.getAgentStatus();
                if (!BusinessContainer.status_03.equals(status)) {
                    throw new RedpException("非新增审批拒绝的代理机构，不能进行删除");
                }
            }
            agentInfoService.delete(idGroup);
        } catch (Exception e) {
            String message = "删除失败";
            log.error(message, e);
            throw new RedpException(message);
        }
    }

    /**
     * 查询省、市、县区
     *
     * @param request
     * @return
     */
    @GetMapping(value = "/provinceSelect2List")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", name = "q", value = "参数", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "path", name = "instId", value = "机构标识", required = true, dataType = "String")
    })
    public String provinceSelect2List(HttpServletRequest request, @NotBlank(message = "{required}") String instId) {
        String q = request.getParameter("q");
        if (null == q) {
            return null;
        }
        q = q.replaceAll("&amp;", "&");
        String[] param = q.split("&");
        if (param.length > 1) {
            return JSON.toJSONString(CommonUtils.dataDictToSelect2(upmpSysParamService, param[1], instId));
        } else {
            return JSON.toJSONString(CommonUtils.dataDictToSelect2(upmpSysParamService, param[0], instId));
        }
    }

    /**
     * 拓展机构下拉框
     *
     * @return
     */
    @GetMapping(value = "/orgExpandSelect2List")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", name = "q", value = "参数", required = true, dataType = "String")
    })
    public Map orgExpandSelect2List(String q) {
        return agentInfoService.orgExpandSelect2List(q);
    }

    /**
     * 该方法适用于 分段方式为：2-固定金额 用时请注意
     */
    @GetMapping(value = "/feeCdSelect2List")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", name = "q", value = "参数", required = true, dataType = "String")
    })
    public Map feeCdSelect2List(QueryRequest request,String q) {

        return feeInfoService.feeInfoRSelect2List(request,q);
    }

    @GetMapping(value = "/agentCdSelect2List")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", name = "q", value = "参数", required = true, dataType = "String")
    })

    public Map agentCdSelect2List(QueryRequest request,String q) {
        return agentInfoService.agentCdSelect2List(request,q);
    }



}
